'use strict'

const { Users, Op } = require('../model')

let fn_product = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || ''
    if (keyword) {
        let list = await Users.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    {name:keyword},
                    {age:keyword}
                ]
            },
            order:['id']
        })
        ctx.body = list
    }else{
        let list = await Users.findAll({
            order:['id']
        })
        ctx.body = list
    }
}
let fn_product_id = async (ctx, next) => {
    let id = ctx.request.params.id
    let arr = await Users.findByPk(id)
    if(arr){
        ctx.body = {
            code:1000,
            data:arr,
            msg:'获取成功'
        }
    }else{
        ctx.body={
            code:400,
            data:null,
            msg:'获取失败'
        }
    }
}
let fn_post = async (ctx, next) => {
    let obj = ctx.request.body
    if(obj){
        let tmpObj = {
            name:obj.name,
            age:obj.age
        }
        Users.create(tmpObj)
        ctx.body={
            code:1000,
            data:tmpObj,
            msg:"新增成功"
        }
    }else{
        ctx.body={
            code:400,
            data:null,
            msg:'数据验证不成功'
        }
    }
}
let fn_put = async (ctx, next) => {
    let id = ctx.request.params.id
    let obj = ctx.request.body
    let users = await Users.findByPk(id)
    if(users){
        await users.update(obj,{
            where:{id:id}
        })
        ctx.body={
            code:1000,
            data:users,
            msg:'修改成功'
        }
    }else{
        ctx.body={
            code:400,
            data:null,
            msg:"修改失败"
        }
    }
}
let fn_delete = async (ctx, next) => {
    let id = ctx.request.params.id
    let users = await Users.findByPk(id)
    if(users){
        await users.destroy({
            where:{id:id}
        })
        ctx.body={
            code:1000,
            data:users,
            msg:'删除成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'删除失败'
        }
    }
}

module.exports={
    'get /product':fn_product,
    'get /product/:id':fn_product_id,
    'post /product':fn_post,
    'put /product/:id':fn_put,
    'delete /product/:id':fn_delete
}